<?php
/*
 * @Author: lokei
 * @Date: 2022-08-16 13:16:33
 * @LastEditors: lokei
 * @LastEditTime: 2022-10-15 13:39:44
 * @Description: 
 */

namespace App\Http\Controllers\Pay\Weixin;

use App\Common\Tools\ResultTool;
use App\Common\Tools\Sn;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Pay\Weixin\Init;
use App\Models\Pay\ConfModel;
use App\Models\Pay\Record\PayRecordModel;
use App\Models\Platform\Conf\ConfMiniappModel;
use App\Models\Platform\ConfModel as PlatformConfModel;
use Illuminate\Http\Request;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Formatter;

class JsapiController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }


    //
    public function pay(Request $request)
    {
        $user = app('auth')->user();
        $instance = Init::getInstance();
        $pay_conf = ConfModel::first();
        if (config('app.proj_identity') != null && config('app.proj_identity') != '') {
            $appid = $request->header('appid');
        } else {
            $miniapp_conf = ConfMiniappModel::first();
            $appid = $miniapp_conf->miniapp_appid;
        }
        $sn = Sn::build_order_no();
        $pay_record = new PayRecordModel();
        $pay_record->uid = $user->uid;
        $pay_record->mode = $request->input('mode');
        $pay_record->pay_mode = '1';
        $pay_record->tid = $sn;
        $pay_record->order_id = $request->input('order_id');
        $pay_record->money = $request->input('money');
        $pay_record->status = '0';
        $pay_record->save();
        $pay_description = '';
        if($request->input('description') != null && $request->input('description') != '') {
            $pay_description = $request->input('description');
        } else {
            $platform_conf = PlatformConfModel::first();
            $pay_description = $platform_conf->name . '支付';
        }
        $resp = $instance
            ->v3->pay->transactions->jsapi
            ->post(['json' => [
                'mchid'        => $pay_conf->mchid,
                'out_trade_no' => $sn,
                'appid'        => $appid,
                'description'  => $pay_description,
                'notify_url'   => env('HOST_URL') . '/api/pay/wx/notify' . ((config('app.proj_identity') != null && config('app.proj_identity') != '') ? ('/' . config('app.proj_identity')) : ''),
                'amount'       => [
                    'total'    => floatVal($request->input('money')) * 100,
                    'currency' => 'CNY'
                ],
                'payer' => [
                    'openid' => $request->input('openid')
                ]
            ]]);
        $jsapi_result = json_decode($resp->getBody()->getContents());
        // 从本地文件中加载「商户API私钥」，「商户API私钥」会用来生成请求的签名
        $merchantPrivateKeyFilePath = 'file://' . env('ATTACHMENT_ROOT') . $pay_conf->key_file;
        $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);
        $params = [
            'appId'     => $appid,
            'timeStamp' => (string)Formatter::timestamp(),
            'nonceStr'  => Formatter::nonce(),
            'package'   => 'prepay_id=' . $jsapi_result->prepay_id,
        ];
        $params += ['paySign' => Rsa::sign(
            Formatter::joinedByLineFeed(...array_values($params)),
            $merchantPrivateKeyInstance
        ), 'signType' => 'RSA'];
        unset($params['appId']);
        $res = ResultTool::success();
        $res['data'] = $params;
        return $res;
    }
}
